﻿using CommHelper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NX5WinServies
{
    public class Sentence
    {
        public class Sword
        {
            public String Word { set; get; }
            public String PS { set; get; }
            public String Mean { set; get; }
            public String Syllable { set; get; }
        }

        public class WordInfo
        {
            public Int32 ID { set; get; }
            public String Mean { set; get; }
            public String Word { set; get; }
            private List<Int32> _Index = new List<int>();
            public List<Int32> Index { set { _Index = value; } get { return _Index; } }
            public Boolean IsExt { set; get; }
        }

        public class DrawDesc
        {
            public String Detail { set; get; }
        }

        public async Task Media()
        {
            DataManager dm = new DataManager();
            DataTable dt = dm.SqlCmd("SELECT * FROM Cus_BookWord_Sentence WHERE IsAudit = 1 AND AiError = 0 and  Media IS NULL").table;
            Log.Write("Sentence-Media", "找到" + dt.Rows.Count + "个需要处理的句子");
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    Log.Write("Sentence-Media", dr["ID"].ToString() + "===========>" + dr["SentenceEn"].ToString());

                    String Desc = await SDKs.AIDoubao.AIBase("将" + dr["SentenceEn"].ToString() + "。根据提供的句子生成一张适合学生认知水平的图片，卡通风格展示句子中的内容。不要解释。"
                        + "返回json格式:{\"Detail\":描述}", false);
                    Console.WriteLine(Desc);
                    Log.Write("Sentence-Media", "描述==============>" + Desc);
                    DrawDesc dd = JsonConvert.DeserializeObject<DrawDesc>(Desc);

                    String Media = await SDKs.AIDoubao.AIDraw(dd.Detail);


                    if (String.IsNullOrEmpty(Media))
                    {
                        Log.Write("Sentence-Media", dr["ID"].ToString() + "=====>空图片===>" + Media);
                        continue;
                    }
                    else if (Media.Length < 40)
                    {
                        Log.Write("Sentence-Media", dr["ID"].ToString() + "=====>空图片===>" + Media);
                        continue;
                    }

                    Console.WriteLine(Media);
                    Log.Write("Sentence-Media", "图片==============>" + Media);
                    dm.SqlCmd("update Cus_BookWord_Sentence set Media = N'" + Media
                        + "' where id = " + dr["ID"].ToString());


                    Log.Write("Sentence-Media", dr["ID"].ToString() + "===================================>" + Media);


                }
                catch (Exception ex)
                {
                    dm.SqlCmd("UPDATE Cus_BookWord_Sentence SET AiError = 1 where ID =  " + dr["ID"].ToString());
                    Log.Write("Sentence-Media", dr["ID"].ToString() + "===================================>" + ex.ToString());
                }
            }
        }

        public async Task Audio()
        {
            DataManager dm = new DataManager();
            DataTable dt = dm.SqlCmd("SELECT * FROM Cus_BookWord_Sentence WHERE IsAudit = 1 AND AiError = 0 and Audio IS NULL").table;
            Log.Write("Sentence-Audio", "找到" + dt.Rows.Count + "个需要处理的句子");
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    Log.Write("Sentence-Audio", dr["ID"].ToString() + "===========>" + dr["SentenceEn"].ToString());

                    String Audio = await SDKs.AIDoubao.AIAudio(dr["SentenceEn"].ToString());
                    if (String.IsNullOrEmpty(Audio))
                    {
                        Log.Write("Sentence-Audio", dr["ID"].ToString() + "=====>空音频===>" + Audio);
                        continue;
                    }
                    else if (Audio.Length < 40)
                    {
                        Log.Write("Sentence-Audio", dr["ID"].ToString() + "=====>空音频===>" + Audio);
                        continue;
                    }

                    dm.SqlCmd("update Cus_BookWord_Sentence set Audio = N'" + Audio
                        + "' where id = " + dr["ID"].ToString());


                    Log.Write("Sentence-Audio", dr["ID"].ToString() + "===================================>" + Audio);


                }
                catch (Exception ex)
                {
                    dm.SqlCmd("UPDATE Cus_BookWord_Sentence SET AiError = 1 where ID =  " + dr["ID"].ToString());
                    Log.Write("Sentence-Audio", dr["ID"].ToString() + "===================================>" + ex.ToString());
                }
            }
        }

        public async Task StartSplit()
        {
            DataManager dm = new DataManager();
            DataTable dt = dm.SqlCmd("SELECT * FROM Cus_BookWord_Sentence WHERE IsAudit = 1 and IsAiSplit = 0 AND AiError = 0").table;
            Log.Write("Sentence", "找到" + dt.Rows.Count + "条需要处理的数据");
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    Log.Write("Sentence", "处理句子=====>" + dr["ID"].ToString() + "====>" + dr["SentenceEn"].ToString());

                    List<Sword> SWS = new List<Sword>();
                    String Result = "";
                    if (dr["AiSplitContent"].ToString() == "")
                    {
                        String Msg = dr["SentenceEn"].ToString() + "把这句话中的所有单词分别给我它们在句子中的中文意思，类似I'm这种缩写看作一个单词，帮我用分音节记忆法分割单词，用/分割；词性用英文缩写,比如名词为n. 。返回json数组格式如下:[{\"Word\":单词,\"Mean\":\"词性. 中文意思\",\"PS\",音标,\"Syllable\":分音节记忆}]，不要解释,本问题只涉及英文学习，不要涉及到文化、政治等和英语学习无关的问题";
                        
                        Result = await SDKs.AIDoubao.AIBase(Msg, false);

                        try
                        {
                            Log.Write("Sentence", "处理结果=====>AI解析====>" + Result);
                            SWS = JsonConvert.DeserializeObject<List<Sword>>(Result);
                        }
                        catch
                        {
                            Log.Write("Sentence", "处理结果=====>AiSplitContent解析");
                            SWS = JsonConvert.DeserializeObject<List<Sword>>(dr["AiSplitContent"].ToString());
                        }
                    }
                    else
                    {
                        Log.Write("Sentence", "处理结果=====>AiSplitContent解析");
                        Result = dr["AiSplitContent"].ToString();
                        SWS = JsonConvert.DeserializeObject<List<Sword>>(dr["AiSplitContent"].ToString());
                    }

                    List<String> WordList = dr["SentenceEn"].ToString().Split(' ').ToList();
                    string pattern = @"^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$";

                    foreach (Sword sw in SWS)
                    {


                        DataTable BaseWord = dm.Procedure("Sys_SentenceSplit", "[{\"Word\":\"" +
                            sw.Word + "\",\"PS\":\"" +
                            sw.PS + "\",\"Mean\":\"" +
                            sw.Mean + "\",\"Syllable\":\"" +
                            (sw.Syllable.IndexOf("/") != -1 ? sw.Syllable : "")
                            + "\",\"Content\":\"" +
                            TransData.Tran(Result.Replace("'", "''")) + "\",\"SentenceId\":\""
                            + dr["ID"].ToString() + "\"}]").table;


                        if (Boolean.Parse(BaseWord.Rows[0]["IsNew"].ToString()))
                        {
                            //音频和方法
                            Log.Write("Sentence", "添加新扩展单词========>" + sw.Word);
                            String Text = "我需要\"" + sw.Word + "\"这个单词的记忆方法(优先音节记忆和词根词缀)，最少给5种记忆方法。返回json数组格式:[{\"Method\":方法名,\"Detail\":说明}]。不要解释";

                            String Audio = await SDKs.AIDoubao.AIAudio(sw.Word);
                            Log.Write("Sentence", "添加扩展单词音频========>" + Audio);
                            String Methods = await SDKs.AIDoubao.AIBase(Text, false);
                            Log.Write("Sentence", "添加扩展单词方法========>" + Methods);
                            dm.SqlCmd("update Base_Words set MP3 = 'https://nx5.abc5g.com/UploadFiles"
                                    + Audio.Replace(System.Configuration.ConfigurationManager.AppSettings["SavePath"], "").Replace("\\", "/")
                                    + "',Methods = N'" +
                                    Methods.Replace("'", "''").Replace("--", "——")
                                    + "' where ID = " + BaseWord.Rows[0]["BaseWordId"].ToString());
                            Log.Write("Sentence", "添加扩展单词========>OK");

                        }
                        else
                        {
                            Log.Write("Sentence", "扩展单词已存在========>" + sw.Word);
                        }

                    }

                    //重构索引  
                    Int32 SentenceId = Int32.Parse(dr["ID"].ToString());
                    DataTable AllWords = dm.SqlCmd("select CB.ID,BW.Word,CB.Mean,CB.BookId from Cus_BookWord CB INNER JOIN Base_Words BW ON CB.BaseWordID = BW.ID where SentenceId = " + SentenceId).table;
                    String En = dr["SentenceEn"].ToString();
                    List<String> SenWords = En.Split(' ').ToList();
                    List<WordInfo> WordIds = new List<WordInfo>();

                    List<WordInfo> WordIndexs = JsonConvert.DeserializeObject<List<WordInfo>>(dr["WordIds"].ToString());
                    foreach (WordInfo WordIndex in WordIndexs)
                    {
                        if (!WordIndex.IsExt)
                        {
                            WordIds.Add(WordIndex);
                        }
                    }

                    foreach (DataRow EachWord in AllWords.Rows)
                    {
                        Boolean IsExt = true;
                        Int32 BookId = Int32.Parse(EachWord["BookId"].ToString());
                        String Word = EachWord["Word"].ToString();
                        String Mean = EachWord["Mean"].ToString();
                        Int32 WordId = Int32.Parse(EachWord["ID"].ToString());

                        Boolean found = false;
                        foreach (WordInfo WordIndex in WordIndexs)
                        {
                            if (WordIndex.ID == WordId && !WordIndex.IsExt)
                            {
                                Console.WriteLine("非扩展==========>" + WordIndex.Word);
                                found = true;
                                break;
                            }
                        }
                        if (found)
                        {
                            continue;
                        }


                        if (BookId != 34)
                        {
                            IsExt = false;
                        }


                        Console.WriteLine(Word);



                        WordInfo item = new WordInfo();
                        item.ID = WordId;
                        item.Mean = Mean;
                        item.Word = Word;
                        item.IsExt = IsExt;
                        //WordId.ID
                        for (Int32 i = 1; i <= SenWords.Count; i++)
                        {
                            String SE = Regex.Replace(SenWords[i - 1], pattern, "");
                            String SW = Regex.Replace(Word, pattern, "");
                            Console.WriteLine(SE + "<=======================>" + SW);
                            if (SE.ToLower() == SW.ToLower())
                            {
                                Console.WriteLine(i);
                                item.Index.Add(i);
                            }
                        }
                        WordIds.Add(item);
                        Console.WriteLine(JsonConvert.SerializeObject(WordIds));
                    }

                    dm.Procedure("Cus_ChangeSentenceWordIndex", "[{\"SentenceId\":" + dr["ID"].ToString()
                                + ",\"WordIds\":\"" + TransData.Tran(JsonConvert.SerializeObject(WordIds)) + "\"}]");



                    dm.SqlCmd("UPDATE Cus_BookWord_Sentence SET IsAiSplit = 1 where ID =  " + dr["ID"].ToString());
                    Log.Write("Sentence", dr["ID"].ToString() + "重构索引=============================================>" + JsonConvert.SerializeObject(WordIds));

                    Log.Write("Sentence", dr["ID"].ToString() + "=============================================>OK");


                }
                catch (Exception ex)
                {
                    dm.SqlCmd("UPDATE Cus_BookWord_Sentence SET IsAiSplit = 0,AiSplitContent=NULL,AiError = 1 where ID =  " + dr["ID"].ToString());
                    Log.Write("Sentence", "ID" + dr["ID"].ToString() + "处理失败===============>" + ex.ToString());
                }

            }
        }
    }
}
